<script setup lang="ts">
defineOptions({
  name: "add"
});

import { ref, onMounted, reactive, toRefs, getCurrentInstance, computed, markRaw } from "vue";
import { PxMessage } from "px-ui";
import { Time } from "@px-ui/icons-vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import { getAllFFU, createWork, queryChildByTypeCodeAndItemValue, getTeamList, getGroupList } from "@/api/machineClass";
import { useTableCloumns } from "./hooks";
import dayjs from "dayjs";
import isToday from "dayjs/plugin/isToday";

dayjs.extend(isToday);

const dialogVisible = defineModel({ type: Boolean, default: false });
const props = withDefaults(defineProps<{ data: Array<Record<string, any>> | null }>(), { data: null });
const commonTableRef = ref<InstanceType<typeof commonTable> | null>(null);
const commonTableKey = ref<string>(Math.random().toString(36).slice(2, 10));
const tableData = ref<Array<Record<string, any>>>([]);
const tableCloumns = computed(() => useTableCloumns(true));

const emits = defineEmits(["submit"]);

const { proxy }: any = getCurrentInstance();

const currentMonthDay = proxy.parseTime(new Date().getTime(), "{y}-{m}-{d}");

const state = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },

  formData: {
    creatorName: "",
    creatorId: "",
    className: "MACHINE",
    excutePerson: "",
    planName: "MAU保养工单",
    eqpGroupId: "",
    estTime: 10,
    planNote: `MAU过滤器临期更换 + ${currentMonthDay}`,
    ruleCode: "",
    outboundReq: "outboundReq",
    teamId: "",
    earlyTime: "2024-08-22 16:47:12",
    lateTime: "2024-09-22 16:47:12",
    systemCode: "SCAVA96E62",
    systemName: "MAU系统",
    eqpId: "ZLROTest",
    eqpName: "ZL-RO303",
    consumableList: [
      {
        subEqpNo: "L1-1",
        sparePartCode: "MAU002",
        meterReading: "1",
        quantity: 1
      },
      {
        subEqpNo: "L1-2",
        sparePartCode: "MAU002",
        meterReading: "1",
        quantity: 2
      },
      {
        subEqpNo: "L1-3",
        sparePartCode: "MAU002",
        meterReading: "1",
        quantity: 3
      }
    ],
    factoryCode: "",
    recipientId: "123",
    recipientName: "zlname",
    used: "过滤器过期更换",
    typeId: 191,
    requestId: "",
    meterReadingMap: {
      TAG_FAC00001: "0.1",
      TAG_FAC00002: "0.2",
      TAG_FAC00003: "0.3",
      TAG_FAC00008: "0.4"
    }
  },
  filterModelLsit: [
    {
      name: "碱性滤膜",
      value: "JX1243"
    },
    {
      name: "碱性滤膜2类",
      value: "JXLM000"
    }
  ],
  componeyList: [
    {
      name: "美埃",
      value: "1"
    }
  ],
  filterList: [],
  dateRange: [],
  peopleList: [],
  rules: {
    // creatorName: [{ required: true, message: "工单创建人不能为空", trigger: "blur" }],
    teamId: [{ required: true, message: "工单执行人不能为空", trigger: "blur" }]
  },
  tableTotalList: [],
  ffuList: [],
  tableList: [],
  // 编辑的表格行
  tableRowEditIndex: undefined,
  // 编辑的表格列
  tableColumnEditIndex: undefined,
  total: 0
});

const { queryParams, rules, total, tableTotalList, tableList, ffuList, peopleList, formData, dateRange } = toRefs(state);
const ticketType = ref("手动");
const ticketTypeList = ref([
  {
    id: 1,
    itemName: "手动"
  }
]);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const loading = ref(false);

const getHour = (s1, s2) => {
  let reDate = /\d{4}-\d{1,2}-\d{1,2} /;
  s1 = new Date((reDate.test(s1) ? s1 : "2018-1-1 " + s1).replace(/-/g, "/"));
  s2 = new Date((reDate.test(s2) ? s2 : "2018-1-1 " + s2).replace(/-/g, "/"));
  let ms = s2.getTime() - s1.getTime();
  if (ms < 0) return 0;
  return Math.floor(ms / 1000 / 60 / 60); //小时
};

const getRowKey = row => {
  return row.subEqpId;
};

const spanMethod = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType) => {
  if (columnIndex === 0) {
    if (rowIndex % row.len === 0) {
      return {
        rowspan: row.len,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};

const cancelFn = () => {
  dialogVisible.value = false;
};

const commitFn = () => {
  if (dateRange.value.length < 1) {
    PxMessage({
      type: "warning",
      message: "请输入计划执行时间"
    });
    return;
  }
  const consumableList = props.data
    .filter(item => item.isReplace)
    .map(item => {
      const { subEqpNo } = item;
      const sparePartCode = "MAU002";
      const quantity = 1;
      return { subEqpNo, sparePartCode, quantity };
    });
  const { typeId, eqpId, eqpName } = props.data[0];
  const param = { ...formData.value, consumableList, typeId, eqpId, eqpName };
  param.estTime = getHour(dateRange.value[0], dateRange.value[1]);
  createWork(param).then(res => {
    if (res) {
      dialogVisible.value = false;
      PxMessage({
        type: "success",
        message: "操作成功"
      });
      emits("submit");
    }
  });
};

const samplePersonIdChange = (val: any) => {
  // formData.dosingPerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};

onMounted(async () => {
  const data: any = await getTeamList({
    className: "MACHINE"
    // factoryCode: "FAC_83abf9",
    // pageNumber: 1,
    // pageSize: 10000000,
    // systemCodeList: []
  });
  // peopleList.value = await getGroupList({ className: "MACHINE" });
  peopleList.value = data;
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
  formData.value.factoryCode = id;
  const resData: any = await queryChildByTypeCodeAndItemValue({
    value: "",
    typeCode: "MCTS"
  });
  formData.value.ruleCode = JSON.parse(resData.filter(el => el.itemValue === "MAUMLX")[0].itemDesc).ruleCode;
  formData.value.eqpGroupId = JSON.parse(resData.filter(el => el.itemValue === "MAUMLX")[0].itemDesc).eqpGroupId;
});
</script>

<template>
  <px-dialog v-model="dialogVisible" title="创建工单" width="1200">
    <div class="tootip-con">
      <div class="con-box">
        <px-form ref="detailruleFormRef" :rules="rules" :model="formData" label-width="110px">
          <div class="form-div">
            <px-row>
              <px-col :span="12">
                <px-form-item label="工单类型">
                  <px-select v-model="ticketType" placeholder="请选择工单类型" style="width: 100%" disabled clearable>
                    <px-option v-for="dict in ticketTypeList" :key="dict.id" :label="dict.itemName" :value="dict.itemName" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="工单创建人" prop="creatorName">
                  <px-input v-model="formData.creatorName" placeholder="工单创建人" /> </px-form-item
              ></px-col>
            </px-row>
            <px-row>
              <px-col :span="12">
                <!-- <px-form-item label="工单执行人" prop="teamId">
                  <px-select v-model="formData.teamId" filterable clearable placeholder="请选择工单执行人" style="width: 100%">
                    <px-option v-for="item in peopleList" :key="item.userId" :label="item.username" :value="item.userId" />
                  </px-select>
                </px-form-item> -->
                <px-form-item label="工单执行人" prop="teamId">
                  <px-select v-model="formData.teamId" filterable clearable style="width: 100%" placeholder="请选择" @change="samplePersonIdChange">
                    <px-option v-for="item in peopleList" :key="item.id" :label="item.name" :value="item.id" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="计划执行时间" style="width: 100%">
                  <px-date-picker
                    v-model="dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :default-time="defaultTime"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </px-form>
        <div v-loading="loading" class="list-info-table">
          <commonTable
            ref="commonTableRef"
            :key="commonTableKey"
            :pagination="false"
            :maxHeight="300"
            :tableCloumns="tableCloumns"
            :list="data"
            :row-key="getRowKey"
            :span-method="spanMethod"
          />
        </div>
        <div class="px-dialog-footer">
          <px-button @click="cancelFn">取消</px-button>
          <px-button type="primary" @click="commitFn">保存</px-button>
        </div>
      </div>
    </div>
  </px-dialog>
</template>

<style lang="scss" scoped>
.tootip-con {
  // display: flex;
  // justify-content: center;
  // width: 100%;
  // height: 100%;

  .con-box {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    padding: 16px;
    background-color: white;

    .px-dialog-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 2002;
      width: 100%;
      height: 50px;
      padding-top: 10px;
      padding-right: 34px;
      text-align: right;
      background: white;
      box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
    }

    .content-title {
      width: 100%;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      letter-spacing: 2px;
    }
  }

  .list-info-table {
    margin-bottom: 20px;
  }
}
</style>
